package com.guit.hrms.wechat.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
@Slf4j
public class WeChatService {
    @Value("${wechat.app-id}")
    private String APP_ID;
    @Value("${wechat.app-secret}")
    private String APP_SECRET;
    @Value("${wechat.template-id}")
    private String TEMPLATE_ID;
    private final OkHttpClient httpClient;

    // 缓存访问令牌
    private String accessToken;
    private long expiresTime;

    public WeChatService() {
        this.httpClient = new OkHttpClient.Builder().build();
    }

    /**
     * 获取访问令牌
     */
    public String getAccessToken() {
        // 如果令牌未过期则直接返回
        if (accessToken != null && System.currentTimeMillis() < expiresTime) {
            return accessToken;
        }

        try {
            String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" +
                    "&appid=" + APP_ID +
                    "&secret=" + APP_SECRET;

            Request request = new Request.Builder()
                    .url(url)
                    .get()
                    .build();

            Response response = httpClient.newCall(request).execute();
            String responseBody = response.body().string();

            JSONObject jsonObject = JSON.parseObject(responseBody);
            accessToken = jsonObject.getString("access_token");
            // 设置过期时间，提前5分钟刷新
            int expiresIn = jsonObject.getIntValue("expires_in");
            expiresTime = System.currentTimeMillis() + (expiresIn - 300) * 1000;

            return accessToken;
        } catch (Exception e) {
            log.error("获取微信访问令牌失败", e);
            throw new RuntimeException("获取微信访问令牌失败", e);
        }
    }

    /**
     * 发送订阅消息
     *
     * @param openId 用户的OpenID
     *               //     * @param templateId 模板ID
     * @param data   模板数据
     *               //     * @param page 小程序页面路径
     */
    public boolean sendSubscribeMessage(String openId, /*String templateId,*/
                                        Map<String, Object> data/*, String page*/) {
        try {
            String accessToken = getAccessToken();
            String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token="
                    + accessToken;

            JSONObject message = new JSONObject();
            message.put("touser", openId);
            message.put("template_id", TEMPLATE_ID);
            message.put("miniprogram_state", "developer");
            message.put("lang", "zh_CN");

//            if (page != null && !page.isEmpty()) {
            message.put("page", "pages/home/home");
//            }

            message.put("data", data);

            RequestBody requestBody = RequestBody.create(
                    MediaType.parse("application/json; charset=utf-8"),
                    message.toJSONString()
            );

            Request request = new Request.Builder()
                    .url(url)
                    .post(requestBody)
                    .build();

            Response response = httpClient.newCall(request).execute();
            String responseBody = response.body().string();

            JSONObject result = JSON.parseObject(responseBody);
            int errcode = result.getIntValue("errcode");

            if (errcode == 0) {
                log.info("发送订阅消息成功, openId: {}", openId);
                return true;
            } else {
                log.error("发送订阅消息失败, openId: {}, 错误码: {}, 错误信息: {}",
                        openId, errcode, result.getString("errmsg"));
                return false;
            }
        } catch (Exception e) {
            log.error("发送微信订阅消息异常", e);
            return false;
        }
    }

//    /**
//     * 模板数据类
//     */
//    @Data
//    @AllArgsConstructor
//    public static class TemplateData {
//        private String value;
//    }
}

